<template>
  <div class="data-table">
    <!-- 筛选控件 -->
    <div class="table-controls">
      <div class="filters">
        <div class="date-filter">
          <label>选择日期：</label>
          <input
              type="date"
              v-model="selectedDate"
              @change="handleDateChange"
          >
        </div>

        <div class="search-group">
<!--          <select v-model="searchType" class="search-type">-->
<!--            <option value="restaurant">餐厅</option>-->
<!--            <option value="department">部门</option>-->
<!--            <option value="dish">菜品</option>-->
<!--          </select>-->
<!--          <input-->
<!--              v-model="searchQuery"-->
<!--              placeholder="输入搜索关键词"-->
<!--              class="search-input"-->
<!--              @keyup.enter="handleSearch"-->
<!--          >-->
          <div v-if="searchLoading" class="search-loading">
            <i class="el-icon-loading"></i>
          </div>
        </div>
        <div class="table-wrapper">
          <!-- 编辑对话框 -->
          <div v-if="showEditDialog" class="modal">
            <div class="modal-content">
              <h3>编辑菜品</h3>
              <form @submit.prevent="saveDish">
                <label>名称：<input v-model="currentDish.name" required></label>
                <label>价格：<input type="number" v-model="currentDish.price" step="0.01" required></label>
                <label>数量：<input type="number" v-model="currentDish.quantity" required></label>
                <div class="dialog-actions">
                  <button type="button" @click="closeDialog">取消</button>
                  <button type="submit">保存</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>

      <!-- 分类操作区 -->
      <div class="category-controls">
        <div class="category-input">
          <input
              v-model="customCategory"
              list="categoryList"
              placeholder="输入或选择分类"
          >
          <datalist id="categoryList">
            <option v-for="c in categorySuggestions" :key="c">{{ c }}</option>
          </datalist>
          <div class="category-controls">
            <!-- 导出操作区 -->
            <div class="export-buttons">
              <!-- 导出全部 -->
              <button
                  class="export-btn"
                  @click="exportAllAsOrder"
              >
                <i class="el-icon-download"></i> 导出全部
              </button>

              <!-- 导出所选 -->
              <button
                  class="export-btn"
                  @click="exportSelectedAsOrder"
                  :disabled="selectedDishes.length === 0"
              >
                <i class="el-icon-s-order"></i> 导出所选（共{{ selectedDishes.length }}项）
              </button>

              <!-- 按日期导出 -->
              <div class="date-export">
                <input
                    type="date"
                    v-model="exportDate"
                    :max="new Date().toISOString().split('T')[0]"
                >
                <button
                    class="export-btn"
                    @click="exportDateAsOrder"
                    :disabled="!exportDate"
                >
                  <i class="el-icon-date"></i> 导出日期
                </button>
                <button class="export-btn" @click="exportExcel">导出当前分类</button>
              </div>
            </div>
          </div>
          <button class="action-btn" @click="applyCategory">应用分类</button>
        </div>
      </div>

      <!-- 数据表格 -->
      <div class="table-wrapper">
        <table>
          <thead>
          <tr>
            <th style="width: 40px;"></th>
            <th>菜品名称</th>
            <th>分类</th>
            <th>所属餐厅</th>
            <th>所属部门</th>
            <th>价格</th>
            <th>数量</th>
            <th style="width: 150px;">操作</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="dish in paginatedData" :key="dish.id">
            <td>
              <input
                  type="checkbox"
                  v-model="selectedDishes"
                  :value="dish.id"
              >
            </td>
            <td>{{ dish.name }}</td>
            <td>{{ dish.category || '未分类' }}</td>
            <td>{{ getRestaurantName(dish.departmentId) }}</td>
            <td>{{ getDepartmentName(dish.departmentId) }}</td>
            <td>¥{{ dish.price.toFixed(2) }}</td>
            <td>{{ dish.quantity }}</td>
            <td>
              <button class="edit-btn" @click="handleEditDish(dish)">编辑</button>
              <button class="delete-btn" @click="handleDeleteDish(dish.id)">删除</button>
            </td>
          </tr>
          </tbody>
        </table>

        <!-- 无数据提示 -->
        <div v-if="paginatedData.length === 0" class="no-data">
          暂无数据
        </div>
      </div>

    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import {
  getDishesByPage,
  updateDish,
  deleteDish,
  batchCategorize,
  exportDishes,
  getCategories, exportSelectedDishes, exportDishesByDate, exportAllDishes
} from "@/api/index.js"
import { debounce } from 'lodash-es'
// 在现有状态定义区域添加
const searchLoading = ref(false) // 初始值为 false
// 状态管理
const selectedDishes = ref([])
const customCategory = ref('')
const categorySuggestions = ref([])
const selectedDate = ref('')
const currentPage = ref(1)
const pageSize = 10
const totalItems = ref(0)
const searchQuery = ref('')
const searchType = ref('dish')
// 导出相关状态
const exportDate = ref('')
// 数据相关
const props = defineProps({
  data: Array,
  departments: Array,
  restaurants: Array  // 新增餐厅数据接收
})

const getRestaurantName = (departmentId) => {
  // 找到对应的部门
  const department = props.departments.find(d => d.id === departmentId)
  if (!department) return '未知部门'

  // 通过restaurantId查找对应餐厅
  const restaurant = props.data.find(r => r.id === department.restaurantId)
  return restaurant?.name || '未知餐厅'
}
const getDepartmentName = (departmentId) => {
  // console.log('departmentId:', departmentId)
  // console.log(props)
  // console.log('props.departments:', props.departments)
  const department = props.departments.find(d => d.id === departmentId)
  return department?.name || '未知部门'
}

// 数据获取
const paginatedData = ref([])
const fetchData = async () => {
  try {
    const res = await getDishesByPage({
      page: currentPage.value,
      size: pageSize,
      selectedDate: selectedDate.value,
      searchType: searchType.value,
      searchQuery: searchQuery.value
    })
    console.log('Fetched data:', res)
    paginatedData.value = res.data
    totalItems.value = res.total
  } catch (error) {
    console.error('数据加载失败:', error)
  }
}

// 初始化加载
onMounted(async () => {
  await fetchData()
  try {
    const res = await getCategories()
    categorySuggestions.value = res.data
  } catch (error) {
    console.error('获取分类失败:', error)
  }
})

const inputPage = ref(1)

watch(currentPage, (newVal) => {
  inputPage.value = newVal
})
// 在现有watch下方添加这些监听器
watch([searchQuery, searchType, selectedDate], () => {
  debouncedSearch()
})

watch(() => props.restaurants, () => {
  debouncedSearch()
})


// 在script setup中添加
const debouncedSearch = debounce(() => {
  handleSearch()
}, 500) // 500ms防抖时间

const handleSearch = async () => {
  try {
    searchLoading.value = true
    const params = {
      page: 1,
      size: pageSize,
      selectedDate: selectedDate.value,
      searchType: searchType.value,
      keyword: searchQuery.value.trim() // 统一参数名为keyword
    }
    switch(searchType.value) {
      case 'restaurant':
        params.restaurantIds = props.restaurants
            .filter(r => r.name.includes(params.keyword))
            .map(r => r.id)
        break
      case 'department':
        params.departmentIds = props.departments
            .filter(d => d.name.includes(params.keyword))
            .map(d => r.id)
        break
      case 'dish':
        // 直接使用keyword参数
        break
    }
    // 获取部门/餐厅ID
    let departmentIds = []
    let restaurantIds = []

    if (searchType.value === 'department') {
      departmentIds = props.departments
          .filter(d => d.name.includes(searchQuery.value.trim()))
          .map(d => d.id)
    }

    if (searchType.value === 'restaurant') {
      restaurantIds = props.restaurants
          .filter(r => r.name.includes(searchQuery.value.trim()))
          .map(r => r.id)
    }
    console.log(params)
    const res = await getDishesByPage({
      ...currentSearchParams,
      departmentIds,
      restaurantIds
    })

    paginatedData.value = res.data
    totalItems.value = res.total
  } catch (error) {
    console.error('搜索失败:', error)
  }
  finally {
    searchLoading.value = false
  }
}

const saveDish = async () => {
  try {
    await updateDish(currentDish.value.id, currentDish.value)
    await fetchData()
    showEditDialog.value = false
  }
  catch (error) {
    console.error('更新失败:', error)
  }
}
const closeDialog = () => {
  showEditDialog.value = false
}
// 日期变化处理
const handleDateChange = () => {
  currentPage.value = 1
  fetchData()
}

// 批量分类
const applyCategory = async () => {
  if (!customCategory.value || selectedDishes.value.length === 0) {
    return alert('请选择菜品并输入分类名称')
  }

  try {
    await batchCategorize({
      dishIds: selectedDishes.value,
      category: customCategory.value
    })
    selectedDishes.value = []
    await fetchData()
    alert('分类成功')
  } catch (error) {
    alert(`分类失败: ${error.message}`)
  }
}

// 导出Excel
const exportExcel = async () => {
  if (!customCategory.value) return alert('请先输入分类名称')

  try {
    const res = await exportDishes(customCategory.value)
    const url = window.URL.createObjectURL(new Blob([res.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `${customCategory.value}_${new Date().toISOString().slice(0,10)}.xls`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    alert(`导出失败: ${error.message}`)
  }
}

// 编辑和删除功能
const showEditDialog = ref(false)
const currentDish = ref({})

const handleEditDish = (dish) => {
  currentDish.value = { ...dish }
  showEditDialog.value = true
}

const handleDeleteDish = async (id) => {
  if (confirm('确定删除该菜品吗？')) {
    try {
      await deleteDish(id)
      await fetchData()
    } catch (error) {
      alert('删除失败: ' + error.message)
    }
  }
}
// 导出全部
const exportAllAsOrder = async () => {
  try {
    const res = await exportAllDishes()
    console.log('导出响应:', res)
    handleExportResponse(res, `全部菜品_${new Date().toISOString().slice(0,10)}.xls`)
  } catch (error) {
    handleExportError(error)
  }
}

// 导出所选
const exportSelectedAsOrder = async () => {
  if (selectedDishes.value.length === 0) {
    return alert('请先选择要导出的菜品')
  }
  try {
    console.log('导出所选菜品:', selectedDishes.value)
    const res = await exportSelectedDishes(selectedDishes.value)

    handleExportResponse(res, `选中菜品_${new Date().toISOString().slice(0,10)}.xls`)
  } catch (error) {
    handleExportError(error)
  }
}

// 按日期导出
const exportDateAsOrder = async () => {
  if (!exportDate.value) return

  try {
    const res = await exportDishesByDate(exportDate.value)
    handleExportResponse(res, `日期订单_${exportDate.value}.xls`)
  } catch (error) {
    handleExportError(error)
  }
}

// 统一处理导出响应
const handleExportResponse = (res, defaultName) => {
  // 处理文件名
  const filename = res.headers['content-disposition']?.split('filename=')[1] || defaultName

  // 创建Blob
  const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })

  // 创建下载链接
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = decodeURIComponent(filename)
  document.body.appendChild(link)

  // 触发下载
  link.click()

  // 清理资源
  setTimeout(() => {
    document.body.removeChild(link)
    URL.revokeObjectURL(link.href)
  }, 100)

  alert('导出成功，开始下载')
}

// 统一处理错误
const handleExportError = (error) => {
  console.error('导出失败:', error)

  let message = '导出失败: '
  if (error.response) {
    message += `${error.response.status} - ${error.response.data.message || '服务器错误'}`
  } else if (error.request) {
    message += '网络连接异常'
  } else {
    message += error.message
  }

  alert(message)
}
</script>

<style scoped>
.data-table {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

/* 筛选控件 */
.table-controls {
  margin-bottom: 20px;
}

.filters {
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
}

.date-filter {
  display: flex;
  align-items: center;
  gap: 8px;
}

.date-filter input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.search-group {
  display: flex;
  gap: 8px;
  align-items: center;
}

.search-type {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #f8f9fa;
  font-size: 14px;
}

.search-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 240px;
  font-size: 14px;
}

/* 分类操作区 */
.category-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 15px;
  flex-wrap: wrap;
}

.category-input {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-grow: 1;
}

.category-input input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  min-width: 240px;
  font-size: 14px;
}

.action-btn, .export-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-btn {
  background: #409eff;
  color: white;
}

.action-btn:hover {
  background: #66b1ff;
}

.export-btn {
  background: #67c23a;
  color: white;
}

.export-btn:hover {
  background: #85ce61;
}

/* 表格样式 */
.table-wrapper {
  overflow-x: auto;
  margin-bottom: 20px;
}

table {
  width: 100%;
  border-collapse: collapse;
  min-width: 800px;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

th {
  background: #f8f9fa;
  font-weight: 600;
  color: #909399;
}

tr:hover {
  background: #f5f7fa;
}

/* 操作按钮 */
.edit-btn, .delete-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  margin: 0 4px;
}

.edit-btn {
  background: #409eff;
  color: white;
}

.edit-btn:hover {
  background: #66b1ff;
}

.delete-btn {
  background: #f56c6c;
  color: white;
}

.delete-btn:hover {
  background: #f78989;
}


/* 无数据提示 */
.no-data {
  padding: 40px;
  text-align: center;
  color: #909399;
  font-size: 14px;
}

/* 响应式处理 */
@media (max-width: 768px) {
  .filters {
    flex-direction: column;
    align-items: stretch;
  }

  .search-group {
    width: 100%;
  }

  .search-input {
    width: 100%;
  }

  .category-controls {
    flex-direction: column;
    align-items: stretch;
  }

  .category-input {
    width: 100%;
  }

  .category-input input {
    min-width: auto;
    flex-grow: 1;
  }

  .pagination-controls {
    flex-direction: column;
    gap: 12px;
  }
}
.export-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  align-items: center;
}

.date-export {
  display: flex;
  gap: 8px;
  align-items: center;

  input[type="date"] {
    padding: 6px;
    border: 1px solid #ddd;
    border-radius: 4px;
  }
}

.export-btn {
  padding: 8px 16px;
  background: #67c23a;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: opacity 0.3s;
  display: flex;
  align-items: center;
  gap: 6px;

  &:hover {
    opacity: 0.9;
  }

  &:disabled {
    background: #c0c4cc;
    cursor: not-allowed;
  }

  i {
    font-size: 14px;
  }
}
.search-loading {
  margin-left: 8px;
  color: #409eff;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>